package com.example.demo.utils;

import com.example.demo.enums.AppHttpCodeEnum;
import com.example.demo.exception.SystemException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class PdfUtils {

    public static String[] extractTextFromPdf(MultipartFile file){
        List<String> pageTexts = new ArrayList<>();
        try (PDDocument document = PDDocument.load(file.getInputStream())) {
            PDFTextStripper textStripper = new PDFTextStripper();
            int numberOfPages = document.getNumberOfPages();
            for (int page = 0; page < numberOfPages; page++) {
                textStripper.setStartPage(page + 1);
                textStripper.setEndPage(page + 1);
                String pageText = textStripper.getText(document);
                pageTexts.add(pageText);
            }
        }catch (IOException e) {
            throw new SystemException(AppHttpCodeEnum.SYSTEM_ERROR);
        }
        return pageTexts.toArray(new String[0]);
    }
    public static String[] extractTextFromSinglePdf(MultipartFile file){
        String text = null;
        try (PDDocument document = PDDocument.load(file.getInputStream())) {
            PDFTextStripper textStripper = new PDFTextStripper();
            text = textStripper.getText(document);
        }
        catch (IOException e) {
            throw new SystemException(AppHttpCodeEnum.SYSTEM_ERROR);
        }
        if(text == null) {
            return null;
        }
        return text.split("\\s+");
    }
}
